package com.lottery.football.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.htmlparser.nodes.TextNode;
import org.htmlparser.tags.Span;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.springframework.stereotype.Service;

import com.lottery.football.mapper.ResultMapper;
import com.lottery.football.pojo.Result;
import com.lottery.football.service.ResultService;
import com.lottery.football.util.ContentParser;

@Service(value="resultService")
public class ResultServiceImpl implements ResultService
{
	@Resource(name="resultMapper")
	private ResultMapper resultMapper;

	@Override
	public List<Result> getResults(String html)
	{
		// 先查出目前库中有结果的最大issue_no
		int maxIssueNo = findMaxIssueNo();
		TableTag resultTable = ContentParser.parseTag(html, TableTag.class, "id", "history_list");
		
		NodeList trList = resultTable.searchFor(TableRow.class, false);
		List<Result> resultList = new ArrayList<Result>();
		
		for (int i = 1; i <= 200; i++)
		{
			TableRow tr = (TableRow) trList.elementAt(i);
			Result result = getResult(maxIssueNo, tr);
			
			if (result == null) {
				break;
			}
			else
			{
				resultList.add(result);
			}
		}
		
		return resultList;
	}
	
	public Integer insert(Result result)
	{
		return resultMapper.insert(result);
	}
	
	private Result getResult(int maxIssueNo, TableRow tr)
	{
		NodeList tdList = tr.searchFor(TableColumn.class, false);
		
		TableColumn issueNoTd = (TableColumn) tdList.elementAt(0);
		int issueNo = Integer.parseInt(((Span)issueNoTd.childAt(0)).getStringText());
		
		// 只取maxIssueNo以后的结果
		if (issueNo <= maxIssueNo)
		{
			return null;
		}
		
		TableColumn dataTd = (TableColumn) tdList.elementAt(1);
		TableColumn moneyTd = (TableColumn) tdList.elementAt(2);
		
		Result result = new Result();
		result.setIssueNo(issueNo);
		System.out.println(issueNo);
		result.setData(((Span) dataTd.childAt(0)).getStringText());
		if (moneyTd.childAt(0) instanceof TextNode)	
		{
			result.setMoney(moneyTd.childAt(0).getText());
		}
		else
		{
			result.setMoney(((Span) moneyTd.childAt(0)).getStringText());
		}
		
		return result;
	}
	
	private int findMaxIssueNo()
	{
		return resultMapper.findMaxIssueNo();
	}

}
